package com.greyu.ysj.service.impl;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.greyu.ysj.config.ResultStatus;
import com.greyu.ysj.entity.CbtAsset;
import com.greyu.ysj.mapper.CbtAssetMapper;
import com.greyu.ysj.model.ResultModel;
import com.greyu.ysj.service.CbtAssetService;

@Service
@Transactional
public class CbtAssetServiceImpl implements CbtAssetService {
	@Autowired
	private CbtAssetMapper cbtAssetMapper;

	public CbtAsset selectAssetByuserId(Integer userId) {
		CbtAsset cbtAsset = this.cbtAssetMapper.selectByPrimaryKeyByUserID(userId);
		if (cbtAsset == null){
			System.out.println("the asset item for this userid is not exists~!");
			return null;
		}
		return cbtAsset;
	}

	@Override
	public double getAsset(Integer userId) {
		CbtAsset cbtAsset = this.cbtAssetMapper.selectByPrimaryKeyByUserID(userId);
		if (cbtAsset == null){
			System.out.println("the asset item for this userid is not exists~!");
			return 0;
		}		
		return cbtAsset.getAsset();
	}

	@Override
	public ResultModel updateAsset(int userId,CbtAsset cbtAsset) {
		
		CbtAsset newAsset = this.cbtAssetMapper.selectByPrimaryKeyByUserID(userId);
		System.out.println("-----------------------------"+newAsset.getAsset());
        if (null == newAsset) {
            return ResultModel.error(ResultStatus.ASSET_NOT_FOUND);
        }
		if(cbtAsset.getAsset() != null) {
			newAsset.setAsset(cbtAsset.getAsset());
			System.out.println("-----------------------------"+newAsset.getAsset());
		}
		if(cbtAsset.getFreezeFlag() != null) {
			newAsset.setFreezeFlag(cbtAsset.getFreezeFlag());
		}
		this.cbtAssetMapper.updateByPrimaryKey(newAsset);
        return ResultModel.ok(newAsset);
	}

	@Override
	public ResultModel save(CbtAsset cbtAsset) {
		try {	
			if ( cbtAsset.getUserId() == null) {
	            return ResultModel.error(ResultStatus.DATA_NOT_NULL);
	        }
			
			cbtAsset.setAsset(0.0);
			cbtAsset.setFreezeFlag(false);
			//insert
	        this.cbtAssetMapper.insert(cbtAsset);
		} catch (Exception e) {
			return ResultModel.error(ResultStatus.INSERT_ERROR);
		}
	        return ResultModel.ok(cbtAsset);
		}

}
